<?php

namespace Jinxing\Admin\Repositories;

use Illuminate\Support\Facades\DB;
use Jinxing\Admin\Models\AdminMenu;
use Littlebug\Repository\Repository;

class AdminMenuRepository extends Repository
{
    public function __construct(AdminMenu $model)
    {
        parent::__construct($model);
    }

    /**
     * 新增用户菜单
     *
     * @param integer      $id          用户id
     * @param string|array $menuIdItems 新增的菜单ID
     *
     * @return bool
     * @throws \Throwable
     */
    public function updateUserMenus($id, $menuIdItems)
    {
        $menuIds = MenuRepository::instance()->findAllHasIds($menuIdItems);

        // 开始使用事务处理
        return DB::transaction(function () use ($id, $menuIds) {
            // 第一步删除数据
           $this->delete(['user_id' => $id]);

            if (empty($menuIds)) {
                return true;
            }

            foreach ($menuIds as $menu_id) {
                $this->create([
                    'menu_id' => $menu_id,
                    'user_id' => $id,
                ]);
            }

            return true;
        });
    }
}
